import React, {useContext} from 'react';
import Toast from 'react-native-root-toast';
import {View, StyleSheet, Alert, ScrollView} from 'react-native';
import {useNavigation} from '@react-navigation/native';
import {useMount, useSafeState, useSetState, useDebounceEffect} from 'ahooks';
import {Button, Text, Input} from '@rneui/base';
import {useSelector, useDispatch} from 'react-redux';
import GlobalContext from '@/GlobalContext';
import {Col, Row, Grid} from 'react-native-easy-grid';
import {ApiHost} from '@/config/common';
import HeaderStyle1 from '@/components/HeaderStyle1';
import globalStyle from '@/style/global.less';

export default () => {
  const navigation = useNavigation();
  const dispatch = useDispatch();
  const token = useSelector(state => state.token.value);
  const accountInfo = useSelector(state => state.accountInfo.value);

  const [formData, setFormData] = useSetState({
    c_password: '',
    confirm_password: '',
  });
  const {c_password, confirm_password} = formData;
  const isAllowSubmit = c_password && c_password === confirm_password;

  const errorTips =
    c_password &&
    confirm_password &&
    (c_password + '').trim() !== (confirm_password + '').trim()
      ? '确认密码不一致'
      : '';

  const updateFormData = (data = {}) => {
    const newData = {
      ...formData,
      ...data,
    };
    setFormData(newData);
  };
  useDebounceEffect(
    () => {
      console.log('formData', formData, 'isAllowSubmit', isAllowSubmit);
    },
    [formData],
    {wait: 5},
  );

  const [submitLoading, setSubmitLoading] = useSafeState(false);
  const submit = async () => {
    setSubmitLoading(true);
    await new Promise(resolve => {
      setTimeout(() => {
        resolve();
      }, 0);
    });
    try {
      let rsObj = undefined;
      try {
        const reqFormData = {
          ...formData,
          c_password: (formData.c_password + '').trim(),
        };
        let res = await fetch(
          `${ApiHost}/account/json/save-password-by-token`,
          {
            headers: {
              'content-type': 'application/json',
              token: token,
            },
            method: 'POST',
            body: JSON.stringify(reqFormData),
          },
        );
        rsObj = await res.json();
        setSubmitLoading(false);
      } catch (e) {
        setSubmitLoading(false);
        Alert.alert('操作失败', e.message);
        return;
      }
      if (!rsObj) {
        Alert.alert('操作失败', '!rsObj');
        return;
      }
      console.log('rsObj', rsObj);
      const {code = 0, msg} = rsObj || {};
      if (code <= 0) {
        Alert.alert('登录失败', msg);
        return;
      }

      let toast = Toast.show(msg, {
        // duration: Toast.durations.LONG,
        duration: 500,
        // position: Toast.positions.CENTER,
        position: 150,
        shadow: true,
        animation: true,
        hideOnPress: true,
        delay: 0,
        onHidden: () => {
          navigation.goBack();
        },
      });
    } catch (e) {
      Alert.alert('系统繁忙', '操作失败');
    }
    setSubmitLoading(false);
  };

  return (
    <>
      <View style={style.box}>
        <HeaderStyle1
          headerRight={() => (
            <View
              style={{
                marginRight: 10,
                minWidth: 80,
              }}>
              <Button
                size="sm"
                loading={submitLoading}
                onPress={submit}
                disabled={!isAllowSubmit}>
                保存
              </Button>
            </View>
          )}>
          设置昵称
        </HeaderStyle1>
        <ScrollView
          style={[
            globalStyle.boxViewBasic,
            {
              flex: 1,
            },
          ]}>
          <Row style={style.list}>
            <Col style={style.title}>
              <Text style={[style.titleTxt, style.accountTxt]}>登录账号</Text>
            </Col>
            <Col style={style.content}>
              <Text style={[style.accountTxt, {marginLeft: 8}]}>
                {accountInfo?.c_loginname}
              </Text>
            </Col>
          </Row>
          <Row style={style.list}>
            <Col style={style.title}>
              <Text style={style.titleTxt}>新密码</Text>
            </Col>
            <Col style={style.content}>
              <Input
                defaultValue={c_password}
                secureTextEntry={true}
                placeholder="填写新密码"
                maxLength={50}
                errorStyle={{
                  display: 'none',
                }}
                onChangeText={v => {
                  updateFormData({
                    c_password: v,
                  });
                }}
              />
            </Col>
          </Row>
          <Row style={style.list}>
            <Col style={style.title}>
              <Text style={style.titleTxt}>确认密码</Text>
            </Col>
            <Col style={style.content}>
              <Input
                defaultValue={confirm_password}
                secureTextEntry={true}
                placeholder="再次填写确认"
                maxLength={50}
                errorStyle={{
                  display: 'none',
                }}
                onChangeText={v => {
                  updateFormData({
                    confirm_password: v,
                  });
                }}
              />
            </Col>
          </Row>
          <View>
            <Text style={style.errorTxt}>{errorTips}</Text>
          </View>
        </ScrollView>
      </View>
    </>
  );
};

const style = StyleSheet.create({
  box: {
    padding: 10,
    flex: 1,
  },
  list: {
    height: 60,
    alignItems: 'center',
  },
  title: {
    width: 100,
    textAlign: 'right',
    flexShrink: 0,
  },
  titleTxt: {
    fontSize: 18,
  },
  accountTxt: {
    color: '#999',
  },
  content: {
    flexGrow: 1,
    flexDirection: 'row',
    alignItems: 'center',
    padding: 0,
    justifyContent: 'flex-start',
  },
  btnBox: {
    marginTop: 50,
  },
  errorTxt: {
    color: '#f05',
    textAlign: 'center',
    marginTop: 2,
  },
});
